package com.example.store.common;

import com.example.store.entity.Time;
import com.example.store.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
@Component
public class SessionListener implements HttpSessionListener {
    @Autowired
    private TimeService timeService;

//    通过监听session摧毁来记录登出时间（当用户没有手动登出的情况下）

    @Override
    public void sessionCreated(HttpSessionEvent se) {

        HttpSession session = se.getSession();
//        设定存活时间（秒）
        session.setMaxInactiveInterval(60*30);

        HttpSessionListener.super.sessionCreated(se);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();

        String userId = (String) session.getAttribute("user");

        if (userId==null){
            return;
        }

        Time time = null;
        if (userId.charAt(0)=='u'||userId.equals("guest")){//用户或者游客

//            记录在线人数,用ServletContext来存,在用户登录时该值会加一,登出时或者session摧毁时减一
            Integer count = (Integer) application.getAttribute("sessions");
            if (count==null||count==0){//已经为零的边界情况
                if(count==null){
                    application.setAttribute("sessions", 0);
                }
                return;
            }
            count--;
            application.setAttribute("sessions", count);
            System.out.println("--------------destroy    "+count+"    ---------------");

            time = Time.createTime(userId, 1);
        }
        else if(userId.charAt(0)=='s'){//开头为”s“的销售人员
            time = Time.createTime(userId, 3);
        }
        else if(userId.equals("root")){//管理员
            time = Time.createTime(userId, 6);
        }

//        获取ip
        String ip = (String) session.getAttribute("ip");;
        if (ip==null){
            ip="--";
        }
        time.setIp(ip);
        session.removeAttribute("user");

//        保存记录到数据库
        timeService.save(time);
        HttpSessionListener.super.sessionDestroyed(se);
    }
}
